package logic

import (
	"MyBlogv2/blog-common/HttpCode"
	define2 "MyBlogv2/blog-common/define"
	"MyBlogv2/blog-common/helper"
	"MyBlogv2/blog-common/models"
	"context"
	"github.com/jinzhu/copier"
	"strconv"

	"MyBlogv2/Servers/UserAction/internal/svc"
	"MyBlogv2/Servers/UserAction/userAction"

	"github.com/zeromicro/go-zero/core/logx"
)

type GetLeaveWordListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewGetLeaveWordListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetLeaveWordListLogic {
	return &GetLeaveWordListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *GetLeaveWordListLogic) GetLeaveWordList(in *UserAction.UserActionRequest) (*UserAction.GetLeaveWordListResponse, error) {
	idStr := in.IdStr
	var leaveWordVoList []models.LeaveWordVo
	db := models.Db.Model(new(models.LeaveWord)).
		Table("t_leave_word lw").
		Select("lw.*,u.avatar,u.nickname").
		Joins("left join sys_user u on lw.user_id = u.id")
	if idStr != "" {
		id, _ := strconv.Atoi(idStr)
		db.Where("lw.id = ?", id)
	}

	db.Where("is_check = ?", define2.IS_CHECK_YES).
		Find(&leaveWordVoList)
	for i, v := range leaveWordVoList {
		var commentCount int64
		models.Db.Model(new(models.Comment)).Where("type = ? and type_id = ?", define2.COMMENT_TYPE_LEAVE_WORD, v.Id).Count(&commentCount)
		leaveWordVoList[i].CommentCount = int(commentCount)
		var likeCount int64
		models.Db.Model(new(models.Like)).Where("type = ? and type_id = ?", define2.LIKE_TYPE_LEAVE_WORD, v.Id).Count(&likeCount)
		leaveWordVoList[i].LikeCount = int(likeCount)
		var favoriteCount int64
		models.Db.Model(new(models.Favorite)).Where("type = ? and type_id = ?", define2.FAVORITE_TYPE_LEAVE_WORD, v.Id).Count(&favoriteCount)
		leaveWordVoList[i].FavoriteCount = int(favoriteCount)

	}
	var leaveWordVoListResponse []*UserAction.LeaveWordVo
	copier.Copy(&leaveWordVoListResponse, &leaveWordVoList)
	for i, v := range leaveWordVoList {
		leaveWordVoListResponse[i].CreateTime = helper.MyTimeToTimestamp(v.CreateTime)
	}

	return &UserAction.GetLeaveWordListResponse{
		Code: int64(HttpCode.SUCCESS),
		Data: leaveWordVoListResponse,
	}, nil
}
